package com.example.first;

import android.content.DialogInterface;
import com.example.first.soundfile.CheapSoundFile;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

import java.io.InputStream;

import com.musicg.wave.Wave;
import com.musicg.wave.WaveFileManager;
import com.musicg.wave.WaveHeader;
//import com.musicg.graphic;


public class MainActivity extends Activity {
    private CheapSoundFile mSoundFile;
    PitchDetector PD;
    Recorder recorderInstance = new Recorder();
    Button  leodbtn;
	Button yinbtn;
   String rawpath;
    Button  playbtn;
    File newfile;
    //Thread th = new Thread(recorderInstance);
     Button simplebtn;
   // // Button playbtn;
  //   Button plotbtn;
    double note;
	//String path;
   // String path2;
	int  musicLength;
	//Wave wave;
	String filen;
    private Handler mHandler;
    AudioRecorder recorder = new AudioRecorder();
    ProgressDialog mProgressDialog;
    boolean mLoadingKeepGoing;
    long mLoadingStartTime;
    long mLoadingLastUpdateTime;
    public void updateText(String msg){
		 TextView textView1 =(TextView)findViewById(R.id.textView1);
 	    textView1.setText(textView1.getText() + "\n" + msg);


	}
	
	public void updateNote(double freq, String name){
	 	double freq2 = frequency.getPitch(freq);
    	String note = frequency.makeNoteSymbol(freq2);
    	
    	   //double frequency = Math.acos((amplitudes[0] + amplitudes[200])/(2*amplitudes[100]));// / (2* 3.14159265);
    	    Log.e("asd","frquncy: " + freq2+  " " + freq);
    	    updateText(name + " Pitch : " + freq);
    	   updateText( name + " Note : " + note);
    	    TextView textView2 =(TextView)findViewById(R.id.textView2);
     	    textView2.setText(note);
	}
	
	public void btnback(View view){
		setContentView(R.layout.activity_main);
	}
	
	
    public void btnSimple(View view) {
    
    	updateNote(PD.getSimple(), "Simple");
      ;
   }
    public void leod(View view){



     }
    public void btnYin(View view) {
        new Thread() {
public void run() {
    	updateNote(PD.getYin(), "YIN");
    updateNote(PD.getleod(), "leod");
}
        }.start();
    	
    }


   

    public void stuff(View view) {

   	}
   

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mHandler = new Handler();

//        leodbtn.setEnabled(false);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    public void copySample() throws IOException{
    	
    	try {
    
		{ 
			  
			 File file;
			AssetManager am = this.getAssets();
			AssetFileDescriptor afd = null;
			  afd = am.openFd( "filesineA.wav");
		Wave	  wave = new Wave(afd.createInputStream());
			    filen = Environment.getExternalStorageDirectory() + java.io.File.separator + "filesineA.wav";
			    WaveFileManager waveFileManager=new WaveFileManager(wave);
	        	 	waveFileManager.saveWaveAsFile(filen);
	        	
	        	 	updateText("Copying Sample");
	        	 	Log.e("asd", "New file created: " + filen);
			    //copyFdToFile(afd.getFileDescriptor(), file);
			
		}
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();}
	}
    
    public Wave readFile (String path3) throws IOException {

                             String      path = path3;
       Log.e("raffile" , path);
        			//path = Environment.getExternalStorageDirectory() + java.io.File.separator + "mic1";
        String path2 = Environment.getExternalStorageDirectory() + java.io.File.separator + "micnew.wav";


        Wave wave = finishOpeningSoundFile(path, path2);
        return wave;

    }

     private Wave finishOpeningSoundFile(String path, String path2) throws IOException {

        updateText("recorded to " + path);

             InputStream inputStream = new FileInputStream(path);

             //initWaveWithInputStream(inputStream);
              long size =  inputStream.available();

         byte[] data = new byte[inputStream.available()];
         Log.e("wa", "avalilable" + inputStream.available());
         byte x;
         int rad =  inputStream.read(data);
         for( int i = 0; i < data.length-1; i++){
             int a = i%2;
             if (a == 0){
                  x = data[i];
                 data[i] = data[i+1];
                 data[i+1] = x;
             }
             }
         inputStream.close();
        WaveHeader head = new WaveHeader();
         //size = data.length * 2;
        // Log.e("wa", "avalilable" + inputStream.available());
         long newsize = 36 + rad;
         head.setChunkSize( newsize);
         Log.e("size", "size : " + newsize);
         head.setChunkId("RIFF");
         head.setFormat("WAVE");
         head.setSubChunk1Id("fmt");
         head.setAudioFormat(1);
         head.setSampleRate(8000);
         head.setChunkSize(newsize);


        head.setSubChunk2Id("data");
         head.setSubChunk2Size(size);
    		Wave wave = new Wave(head,data);
         //  wave.
        // wave.
        Log.e("wave", wave.toString())   ;
         updateText(wave.toString());
         Log.e("wave", wave.getWaveHeader().toString())   ;
         WaveFileManager waveFileManager=new WaveFileManager(wave);
         waveFileManager.saveWaveAsFile(path2);
        Log.e("length", "length : " + wave.length());
       return wave;    }
   


    public void playsound(View view) throws IOException {
    	//String name = recorder.stop();

        recorderInstance.setRecording(false);
     //   try {

           // th.wait();
         //  recorderInstance = null;
      //  } catch (InterruptedException e) {
      //      e.printStackTrace();
     //   }


        final ScrollView scroller = (ScrollView) findViewById(R.id.scroller);
        scroller.post(new Runnable() {
            public void run() {
                scroller.fullScroll(ScrollView.FOCUS_DOWN);
            }});
       // newfile.deleteOnExit();
    }
    public void playsound2(View view) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {

    	MediaPlayer mp= new MediaPlayer(); 
    //	mp.setDataSource(path);
    	mp.prepare();
    	mp.setVolume(1.0f, 1.0f);
    	mp.start();

     }
    
    public void readmic(View view) throws IOException{

        Thread th = new Thread(recorderInstance);
         playbtn.setEnabled(false) ;
        playbtn.setText("WAIT");
        updateText("RECORDING : 2 sec");
        recorderInstance.setFileName(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test.pcm"));
        th.start();

        recorderInstance.setRecording(true);
        synchronized (this) {
            try {
                updateText("RECORDING : 3 sec") ;

                this.wait(1000);
                updateText("RECORDING : 2 sec") ;
                this.wait(1000);
                updateText("RECORDING : 1 sec")    ;
                this.wait(1000);
                updateText("RECORDING : 0 sec")    ;

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        recorderInstance.setRecording(false);
        updateText("Recording finished");
        try {
            th.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
         rawpath = recorderInstance.getFileName().getAbsolutePath();
        Log.e("wae", rawpath);
        //playsound2(view);
        final Wave wave = readFile(rawpath);

        updateText("Wav file saved to " + recorderInstance.getFileName().getAbsolutePath());
        updateText("Running Pitch detector");
        boolean fini = false;
        new Thread() {
            public void run() {

                PD = new PitchDetector(wave);
                note = PD.getYin();
                Runnable runnable = new Runnable() {
                    public void run() {
                        updateNote(note, "YIN");
                        playbtn.setEnabled(true) ;
                        playbtn.setText("GO");
                    }
                };
                mHandler.post(runnable);
            }
        }.start();


    }

    
    }

